package com.mavenq.fly.websocket.handler;

import com.mavenq.fly.websocket.service.WSConnectionService;
import com.mavenq.fly.websocket.entity.WSMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.Map;

@Slf4j
@Component
public class BroadcastWebSocketHandler extends AbstractWSHandler {

    public BroadcastWebSocketHandler(WSConnectionService connectionService) {
        super(connectionService);
    }

    @Override
    protected void onMessage(WebSocketSession session, WSMessage msg) {
        if ("ping".equalsIgnoreCase(msg.getType())) {
            sendPong(session);
            return;
        }
        // 广播给所有连接
        connectionService.broadcast(msg);
        log.info("广播消息：userId={}, type={}, content={}", extractUserId(session.getAttributes()), msg.getType(), msg.getContent());
    }

    private String extractUserId(Map<String, Object> attrs) {
        return (String) attrs.getOrDefault("userId", "unknown");
    }
}